# Core configuration management
import os
from typing import Optional, Dict, Any
from pydantic import validator
from pydantic_settings import BaseSettings
from enum import Enum


class NovelProject(str, Enum):
    DOULUO_DALU = "douluo_dalu"  # 斗罗大陆
    DOUPO_CANGQIONG = "doupo_cangqiong"  # 斗破苍穹
    CHANGAN_TWELVE = "changan_twelve"  # 长安十二时辰


class Settings(BaseSettings):
    # 应用基础配置
    PROJECT_NAME: str = "数字人小说剧情讨论网站"
    VERSION: str = "1.0.0"
    DEBUG: bool = False
    API_V1_STR: str = "/api/v1"
    PORT: int = 8000
    
    # 数据库配置
    DATABASE_HOST: str = "rm-bp168czzpsknw32k4mo.mysql.rds.aliyuncs.com"
    DATABASE_PORT: int = 3306
    DATABASE_USER: str = "root"
    DATABASE_PASSWORD: str = "Yunren123"
    DATABASE_NAME: str = "echo_role"
    
    # DeepSeek API配置
    DEEPSEEK_API_KEY: str = "sk-2e35a2b837a64ab6b723b92ae4944334"
    DEEPSEEK_MODEL: str = "deepseek-chat"
    DEEPSEEK_API_HOST: str = "https://api.deepseek.com/v1"
    DEEPSEEK_MAX_TOKENS: int = 4000
    DEEPSEEK_TEMPERATURE: float = 0.7
    
    # 阿里云配置
    ALIYUN_REGION: str = "cn-shanghai"
    ALIYUN_ACCESS_KEY_ID: str = "LTAI5tSUYrH55wwvHZ3rLpzL"
    ALIYUN_ACCESS_KEY_SECRET: str = "1R4AejbxN6iBocE4OqlbCiplMPteWo"
    
    # 阿里云OSS配置
    ALIYUN_OSS_BUCKET: str = "echo-role"
    ALIYUN_OSS_ENDPOINT: str = "oss-cn-hangzhou.aliyuncs.com"
    ALIYUN_OSS_UPLOAD_DIR: str = "uploads"
    ALIYUN_OSS_IMAGE_DIR: str = "uploads/image"
    ALIYUN_OSS_AUDIO_DIR: str = "uploads/audio"
    ALIYUN_OSS_APPLICATION_DIR: str = "uploads/application"
    
    # 通用OSS配置
    OSS_PROVIDER: str = "aliyun" 
    OSS_ACCESS_KEY: str = "LTAI5tSUYrH55wwvHZ3rLpzL"
    OSS_SECRET_KEY: str = "1R4AejbxN6iBocE4OqlbCiplMPteWo"
    OSS_BUCKET: str = "echo-role"
    OSS_ENDPOINT: str = "oss-cn-hangzhou.aliyuncs.com"
    OSS_REGION: str = "cn-hangzhou"
    OSS_CUSTOM_DOMAIN: Optional[str] = None
    OSS_MAX_FILE_SIZE: int = 50 * 1024 * 1024  # 50MB
    OSS_ALLOWED_CONTENT_TYPES: set = {
        "image/jpeg", "image/png", "image/gif", "image/webp",
        "audio/mpeg", "audio/mp3", "audio/wav", "audio/ogg", "audio/webm", "audio/m4a",
        "video/mp4", "video/webm", "video/ogg",
        "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    }
    
    # 阿里云智能语音项目配置
    ALIYUN_TTS_PROJECTS: Dict[str, str] = {
        NovelProject.DOULUO_DALU: "zb8RwXrsKhJAWWkD",  # 斗罗大陆
        NovelProject.DOUPO_CANGQIONG: "WMwUmXFV7NdP6GAz",  # 斗破苍穹
        NovelProject.CHANGAN_TWELVE: "ipVMwz85eHehrPdQ"  # 长安十二时辰
    }
    
    # JWT认证配置
    SECRET_KEY: str = "0oDF21BTfDc8zIY93XJ-ZbE64xeB731jB3Bp_RYN2x0"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    REFRESH_TOKEN_EXPIRE_DAYS: int = 7
    ALGORITHM: str = "HS256"
    
    # 文件上传配置
    UPLOAD_DIR: str = "uploads"
    STATIC_DIR: str = "static"  # 静态文件目录
    MAX_FILE_SIZE: int = 10 * 1024 * 1024  # 10MB
    ALLOWED_IMAGE_TYPES: set = {"image/jpeg", "image/png", "image/gif"}
    ALLOWED_AUDIO_TYPES: set = {"audio/wav", "audio/mp3", "audio/m4a"}
    ALLOWED_MODEL_TYPES: set = {"application/octet-stream", "model/gltf+json"}
    
    # CORS配置
    BACKEND_CORS_ORIGINS: list = [
        "http://localhost:3000",
        "http://localhost:8080",
        "http://localhost:5173"
    ]
    
    # Redis配置（用于缓存和会话）
    REDIS_URL: str = "redis://localhost:6379"
    
    # WebSocket配置
    WS_MAX_CONNECTIONS: int = 100
    WS_HEARTBEAT_INTERVAL: int = 30
    
    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    
    # 服务器配置
    SERVER_HOST: str = "0.0.0.0"
    SERVER_PORT: int = 8000
    
    @property
    def database_url(self) -> str:
        return f"mysql+aiomysql://{self.DATABASE_USER}:{self.DATABASE_PASSWORD}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}"
    
    @property
    def sync_database_url(self) -> str:
        return f"mysql+pymysql://{self.DATABASE_USER}:{self.DATABASE_PASSWORD}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}"
    
    def get_tts_project_id(self, novel_type: NovelProject) -> str:
        return self.ALIYUN_TTS_PROJECTS.get(novel_type, self.ALIYUN_TTS_PROJECTS[NovelProject.DOULUO_DALU])
    
    def get_oss_upload_path(self, file_type: str, filename: str) -> str:
        if file_type.startswith("image/"):
            return f"{self.ALIYUN_OSS_IMAGE_DIR}/{filename}"
        elif file_type.startswith("audio/"):
            return f"{self.ALIYUN_OSS_AUDIO_DIR}/{filename}"
        elif file_type.startswith("application/"):
            return f"{self.ALIYUN_OSS_APPLICATION_DIR}/{filename}"
        else:
            return f"{self.ALIYUN_OSS_UPLOAD_DIR}/{filename}"
    
    def get_oss_public_url(self, object_key: str) -> str:
        return f"https://{self.ALIYUN_OSS_BUCKET}.{self.ALIYUN_OSS_ENDPOINT}/{object_key}"
    
    @property
    def server_url(self) -> str:
        return f"http://localhost:{self.SERVER_PORT}"
    
    @validator("SECRET_KEY", pre=True)
    def validate_secret_key(cls, v):
        if v == "your-secret-key-here":
            import secrets
            return secrets.token_urlsafe(32)
        return v
    
    class Config:
        env_file = ".env"
        case_sensitive = True


# 创建全局设置实例
settings = Settings()


def get_settings() -> Settings:
    return settings 